package org.kermeta.spem.activityautomation.eclipse.newtomcatserver.actions;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.wst.server.core.IRuntime;
import org.eclipse.wst.server.core.IRuntimeType;
import org.eclipse.wst.server.core.IRuntimeWorkingCopy;
import org.eclipse.wst.server.core.IServerType;
import org.eclipse.wst.server.core.IServerWorkingCopy;
import org.eclipse.wst.server.core.ServerCore;
import org.kermeta.spem.activityautomationmanager.ActivityAutomation;

public class NewTomcatServer implements ActivityAutomation {

	public NewTomcatServer() {
		// TODO Auto-generated constructor stub
	}

	@Override
	//Creation of a new and preconfigured Tomcat server
	public void run(String contextModelPath) {
		
		//Creation of a Tomcat runtime configuration
		IRuntimeType[] runtimeTypes = ServerCore.getRuntimeTypes();
		for(IRuntimeType runtimeType : runtimeTypes){
			if(runtimeType.getName().equals("Apache Tomcat v7.0")){
				try {
					IRuntimeWorkingCopy runtimeWorkingCopy = runtimeType.createRuntime(null, new NullProgressMonitor());
					runtimeWorkingCopy.setLocation(new Path("C:\\Program Files\\Apache Software Foundation\\Tomcat 7.0"));
					IStatus status = runtimeWorkingCopy.validate(new NullProgressMonitor());
					System.out.println("status code = "+status.getCode());
					System.out.println("status message = "+status.getMessage());
					runtimeWorkingCopy.save(false, new NullProgressMonitor());
					System.out.println("save done");
				} catch (CoreException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		//Salvage of the newly created runtime
		IRuntime myRuntime = null;
		IRuntime[] runtimes = ServerCore.getRuntimes();
		for(IRuntime runtime : runtimes){
			if(runtime.getName().equals("Apache Tomcat v7.0")){
				myRuntime = runtime;
			}
		}
		
		//Creation of a new server with the newly created runtime configuration
		IServerType[] serverTypes = ServerCore.getServerTypes();
		for(IServerType serverType : serverTypes){
			if(serverType.getName().equals("Tomcat v7.0 Server")){
				try {
					IServerWorkingCopy serverWorkingCopy = serverType.createServer(null, null, myRuntime, null);
					serverWorkingCopy.save(false, new NullProgressMonitor());
				} catch (CoreException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

}
